package com.xiaoyang.billiards.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.xiaoyang.billiards.architecture.common.Errors.UserError;
import com.xiaoyang.billiards.architecture.common.exception.ServiceException;
import com.xiaoyang.billiards.architecture.common.result.Result;
import com.xiaoyang.billiards.consts.BilliardConst;
import com.xiaoyang.billiards.enums.BilliardEnums;
import com.xiaoyang.billiards.params.UserParam;
import com.xiaoyang.billiards.response.UserResponse;
import com.xiaoyang.billiards.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class UserController {

    @Resource
    private UserService userService;
    @PostMapping("/login")
    public Result<UserResponse> login(@RequestBody UserParam userParam){
        System.out.println(Thread.currentThread().getName());
        UserResponse userResponse =  userService.query(userParam);
        if (userResponse.getMsg().equals("用户名或密码错误")){
            return Result.error(UserError.TOKEN_ERROR,"用户名或密码错误");
        }
        // 第二步：根据账号id，进行登录
        StpUtil.login(userResponse.getUserId());
        BilliardConst.token = StpUtil.getTokenValue();
        return Result.ok(new UserResponse(userResponse.getUserId(),BilliardEnums.LOGIN.getDesc(),StpUtil.getTokenValue()));
    }

    @PostMapping("/info")
    public Result<UserResponse> info(){
        int userId;
        try {
            // 报错空指针 Cannot invoke "Object.toString()" because the return value of "cn.dev33.satoken.stp.StpUtil.getLoginIdByToken(String)" is null
            userId = Integer.parseInt(StpUtil.getLoginIdByToken(BilliardConst.token).toString());
        } catch (NumberFormatException e) {
            throw new ServiceException(UserError.TOKEN_ERROR,e.getMessage());
        }
        UserParam userParam = new UserParam();
        userParam.setUserId(userId);
        UserResponse userResponse =  userService.query(userParam);
        if (userResponse.getMsg().equals("用户名或密码错误")){
            return Result.error(UserError.TOKEN_ERROR,"用户名或密码错误");
        }
        return Result.ok(userResponse);
    }

    @PostMapping("/editUser")
    public Result<String> editUser(@RequestBody UserParam userParam){
        // update user set user_name = ?,user_password = ?,user_phone = ?,user_call = ? where user_id = ?
        Integer result = userService.updateByUserParam(userParam);
        return Result.ok("修改成功");
    }

    @PostMapping("/user")
    public Result<List<UserResponse>> user(){
        List<UserResponse> userResponseList = userService.queryForList(null);
        return Result.ok(userResponseList);
    }

    @PostMapping("/addUser")
    public Result<String> addUser(@RequestBody UserParam userParam){
        Integer result = userService.add(userParam);
        return Result.ok("添加成功");
    }

    @PostMapping("/changeState")
    public Result<String> changeState(@RequestBody UserParam userParam){
        // update user set user_state = ? where user_id = ?
        userService.updateByUserParam(userParam);
        return Result.ok("更改成功");
    }

    @PostMapping("/deleteUser")
    public Result<String> deleteUser(@RequestBody UserParam userParam){
        // delete from user where user_id = ?
        userService.delete(userParam);
        return Result.ok("删除成功");
    }

    @PostMapping("/batchDeleteUser")
    public Result<String> batchDeleteUser(@RequestBody List<Integer> userIds){
        // delete from user where user_id in (?)
        if (userIds.isEmpty()){
            throw new ServiceException(UserError.DELETE_ERROR,"用户id不能为空");
        }
        userService.batchDelete(userIds);
        return Result.ok("删除成功");
    }

}
